# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import random
from logging import getLogger

import scrapy
from scrapy import signals, crawler

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy.http import HtmlResponse
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

from spider_source.config import TargetWeb
from spider_source.utils.avenger import Avenger


class SpiderSourceSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class SpiderSourceDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls(user_agent_list=crawler.settings.get("USER_AGENT_LIST"))
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def __init__(self, user_agent_list):
        self.logger = getLogger(__name__)
        options = Options()
        options.add_argument("--headless")
        options.add_argument("--no-sandbox")
        # 禁用gpu
        options.add_argument("--disable-gpu")
        # 隐藏滚动条
        options.add_argument("--hide-scrollbars")
        # 禁止加载图片
        options.add_argument("--blink-settings=imagesEnabled=false")
        options.add_argument('--user-agent={0}'.format(random.choice(user_agent_list)))
        # options.add_argument('--proxy-server=http://{0}'.format(random.choice(ip_list)))
        # 配置谷歌无头浏览器
        self.browser = webdriver.Chrome(options=options)

    def process_request(self, request, spider):
        spider_config = TargetWeb.get(spider.name)
        class_name_list = spider_config.get("class_name")
        self.browser.get(request.url)
        flag = False
        for class_name in class_name_list:
            try:
                WebDriverWait(self.browser, spider_config.get("wait_time")). \
                    until(lambda x: x.find_element_by_class_name(class_name))
                flag = True
            except Exception as e:
                self.logger.error('errback {} ResponseFailed;class_name:{} not fount'.format(request.url, class_name))

            if flag:
                break

        if not flag:
            return HtmlResponse(url=request.url, body="", status=404)

        return HtmlResponse(url=request.url, body=self.browser.page_source, encoding="utf-8", status=200)

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest

        if response.status == 200:
            # 提取详情页的连接，然后存入redis
            Avenger.dispatcher(spider.name, response, **TargetWeb.get(spider.name))

        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
